package cn.xyt.util;

import cn.xyt.dto.Form;
import cn.xyt.dto.SystemProperty;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WebRequestCache {
	private static final Logger LOG = LoggerFactory.getLogger(WebRequestCache.class);
	public static Cache<String, Object> cache = null;
	@Autowired
	private SystemProperty systemProperty;

	public static <T> T get(String key) {
		T message = null;
		try {
			message =  (T) cache.getIfPresent(key);
		} catch (Exception e) {
			LOG.debug("get web request[key={}] from cache faild, error={}", key, e.getMessage());
		}
		return message;
	}

	public static void set(String key, Object message) {
		cache.put(key, message);
	}

	public static void remove(String key) {
		try {
			cache.invalidate(key);
		} catch (Exception e) {
			LOG.debug("remove web request[key={}] from cache faild, error={}", key, e.getMessage());
		}
	}

	@PostConstruct
	public void init() {
		if (cache == null) {  //设置过期时间
			cache = CacheBuilder.newBuilder().expireAfterWrite(this.systemProperty.getWebRequestTimeout().intValue() + 10, TimeUnit.SECONDS).build();
		}
	}

	@PreDestroy
	public void destroy() {
		try {
			cache.invalidateAll();
		} catch (Exception e) {
			LOG.debug("remove all web request from cache faild, error={}", e.getMessage());
		}
	}
}
